package com.gateway.video.rtsp.stream.pull;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.kohsuke.MetaInfServices;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@MetaInfServices(PullVideoStream.class)
public class RtspPullVideoStream implements PullVideoStream {

    @Override
    public void pull(PullVideoConfig pullVideoConfig) {
        var source = pullVideoConfig.getSource();
        if (source != null) {
            try {
                Map<String, String> options = source.getOptions() == null ? new HashMap<>() : source.getOptions();
                if (options.get(PullConstants.RTSP_TRANSPORT) == null) {
                    options.put(PullConstants.RTSP_TRANSPORT, PullConstants.DEFAULT_RTSP_TRANSPORT);
                }

                Map<String, String> videoOptions = source.getVideoOptions() == null ? new HashMap<>() : source.getVideoOptions();
                if (videoOptions.get(PullConstants.VCODEC) == null) {
                    videoOptions.put(PullConstants.VCODEC, PullConstants.DEFAULT_VCODEC);
                }

                var grabber = FFmpegFrameGrabber.createDefault(source.getUrl());
                grabber.setOptions(options);
                grabber.setVideoOptions(videoOptions);
                grabber.setImageWidth(Optional.ofNullable(source.getImageWidth()).orElse(450));
                grabber.setImageHeight(Optional.ofNullable(source.getImageHeight()).orElse(240));
                grabber.setVideoBitrate(Optional.ofNullable(source.getVideoBitrate()).orElse(3500));

                PullSource.getInstance().register(grabber);

                if (source.isEnabled()) {
                    grabber.start();
                }
            } catch (FrameGrabber.Exception e) {
                if (log.isErrorEnabled()) {
                    log.error("Video server fail of source={} damage", source, e);
                }
            }
        } else {
            if (log.isWarnEnabled()) {
                log.warn("Video server no source");
            }
        }
    }
}
